package com.gecba.minio.service;

import com.gecba.minio.enums.ContentType;
import io.minio.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;


@Slf4j
@Service
public class MinIoServices {

    @Autowired
    private MinioClient minioClient;

    /**
     * 判断bucket是否存在
     * @param bucketName
     * @return true 存在，false 不存在
     */
    @SneakyThrows(Exception.class)
    public boolean bucketExists(String bucketName){
       return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    /**
     * 文件上传
     * @param bucketName
     * @param fileName
     * @param inputStream
     * @param contentType
     * @return
     */
    @SneakyThrows(Exception.class)
    public ObjectWriteResponse putObject(String bucketName, String fileName, InputStream inputStream, ContentType contentType){
        PutObjectArgs pubObjectArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .contentType(contentType.toString())
                .stream(inputStream, inputStream.available(), -1)
                .build();
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(pubObjectArgs);
        log.info("文件【{}】上传成功",objectWriteResponse.object());
        return objectWriteResponse;
    }

    @SneakyThrows(Exception.class)
    public void deleteObject(String bucketName, String fileName){
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .build();
        minioClient.removeObject(removeObjectArgs);
    }


}
